//
//  OtherInformationViewController.swift
//  IDF
//
//  Created by icbbetter on 2018/5/17.
//  Copyright © 2018年 Jesse.chen. All rights reserved.
//

import UIKit
import BEMCheckBox
import INTULocationManager
import Alamofire
import SVProgressHUD
import ContactsWrapper

class OtherInformationViewController: BaseViewController {

    var otherInfo: OtherInfo!
    
    @IBOutlet weak var view_1: UIView!
    @IBOutlet weak var view_2: UIView!
    @IBOutlet weak var view_3: UIView!
    let checkBox_1 = BEMCheckBox(frame: CGRect(x: 20, y: 15, width: 20, height: 20))
    let checkBox_2 = BEMCheckBox(frame: CGRect(x: 20, y: 15, width: 20, height: 20))
    let checkBox_3 = BEMCheckBox(frame: CGRect(x: 20, y: 15, width: 20, height: 20))
    let locationManager = INTULocationManager.sharedInstance()
    let contacts = ContactsWrapper()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "Other Information"
        
        checkBox_1.boxType = .square
        checkBox_1.onAnimationType = .fill
        checkBox_1.offAnimationType = .fill
        checkBox_1.lineWidth = 2
        checkBox_1.onFillColor = UIColor(hexString: "8cadf5")!
        checkBox_1.onTintColor = UIColor(hexString: "8cadf5")!
        checkBox_1.onCheckColor = .white
        checkBox_1.isEnabled = false
        view_1.addSubview(checkBox_1)
        
        checkBox_2.boxType = .square
        checkBox_2.onAnimationType = .fill
        checkBox_2.offAnimationType = .fill
        checkBox_2.lineWidth = 2
        checkBox_2.onFillColor = UIColor(hexString: "8cadf5")!
        checkBox_2.onTintColor = UIColor(hexString: "8cadf5")!
        checkBox_2.onCheckColor = .white
        view_2.addSubview(checkBox_2)
        
        checkBox_3.boxType = .square
        checkBox_3.onAnimationType = .fill
        checkBox_3.offAnimationType = .fill
        checkBox_3.lineWidth = 2
        checkBox_3.onFillColor = UIColor(hexString: "8cadf5")!
        checkBox_3.onTintColor = UIColor(hexString: "8cadf5")!
        checkBox_3.onCheckColor = .white
        view_3.addSubview(checkBox_3)
        
        if otherInfo.contactsNum == 1 {
            checkBox_1.on = true
        }
        
        if otherInfo.callLogNum == 1 {
            checkBox_3.on = true
        }
        
        if otherInfo.location == 1 {
            checkBox_2.on = true
        }
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func syncLoaction(_ sender: UIButton) {
        
        locationManager.requestLocation(withDesiredAccuracy: .neighborhood,
                                        timeout: 10.0,
                                        delayUntilAuthorized: true) { (currentLocation, achievedAccuracy, status) in
                                            if (status == INTULocationStatus.success) {
                                                let dic = [
                                                    "locationX": "\(currentLocation!.coordinate.longitude)",
                                                    "locationY": "\(currentLocation!.coordinate.latitude)"
                                                ]
                                                let request = RequestData(path: "User/PostUserLocation", method: .post, param: dic, encoding: JSONEncoding.default)
                                                
                                                SVProgressHUD.show()
                                                
                                                netRequest(request).then { [weak self] _ -> Void in
                                                    self?.checkBox_2.on = true
                                                }
                                                // Request succeeded, meaning achievedAccuracy is at least the requested accuracy, and
                                                // currentLocation contains the device's current location
                                            }
                                            else if (status == INTULocationStatus.timedOut) {
                                                // Wasn't able to locate the user with the requested accuracy within the timeout interval.
                                                // However, currentLocation contains the best location available (if any) as of right now,
                                                // and achievedAccuracy has info on the accuracy/recency of the location in currentLocation.
                                            }
                                            else {
                                                // An error occurred, more info is available by looking at the specific status returned.
                                            }
        }
        
    }
    @IBAction func syncContact(_ sender: UIButton) {

        contacts.getContactsWithKeys([CNContactFamilyNameKey as CNKeyDescriptor, CNContactGivenNameKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor], containerId: nil) { (arr, error) in
            var contactArr : [[String: String]] = []
            var callLogArr : [[String: String]] = []
            arr?.forEach({ (contact) in
                let name = contact.familyName + contact.givenName
                if contact.phoneNumbers.count > 0 && name != "" {
                    var dic = [
                        "name": name,
                        "phone": contact.phoneNumbers[0].value.stringValue
                    ]
                    contactArr.append(dic)
                    dic["callTime"] = "2018-04-15 18:00:11"
                    callLogArr.append(dic)
                }
            })
            let request_1 = RequestData(path: "User/PostUserConcats?userId=\(appUser.userId!)", method: .post, paramArr: contactArr)
            SVProgressHUD.show()
            netRequest(request_1).then { [weak self] _ -> Void in
                self?.checkBox_1.on = true
            }
            let request_2 = RequestData(path: "User/PostUserCallRecord?userId=\(appUser.userId!)", method: .post, paramArr: contactArr)
            netRequest(request_2)
                
            }
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
